package com.wanmait.happyheating.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.wanmait.happyheating.pojo.*;
import com.wanmait.happyheating.service.*;
import com.wanmait.happyheating.util.PictureUtils;
import com.wanmait.happyheating.util.Result;
import com.wanmait.happyheating.util.workersJWTUtils;
import lombok.Synchronized;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/worker")
public class WorkerOrdersController {
    @Resource
    private WorkersService workersService;
    @Resource
    private WorkersLogService workersLogService;
    @Resource
    private OrdersinfoService ordersinfoService;
    @Resource
    private StateService stateService;
    @Resource
    private HeatingNumberService heatingNumberService;
    @Resource
    private FaultTypeService faultTypeService;
    @Resource
    private MaterialsTypeService materialsTypeService;
    @Resource
    private MaterialsNameService materialsNameService;
    @Resource
    private MaterialsUseService materialsUseService;

    /**
     * 维修工人登录
     */
    @RequestMapping("login")
    public Result login(@RequestBody Workers worker) {
        System.out.println("qqqqqqqqqqqqqqqqqqqqqqq");
        LambdaQueryWrapper<Workers> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Workers::getName, worker.getName());
        wrapper.eq(Workers::getPass, worker.getPass());
        Workers workers = workersService.getOne(wrapper);
        if (workers != null) {
            WorkersLog workersLog = new WorkersLog();
            workersLog.setIp("ip");
            workersLog.setWorkers(workers);
            workersLog.setWorkersId(workers.getId());
            workersLog.setInputTime(new Timestamp(System.currentTimeMillis()));
            workersLogService.save(workersLog);
            String token = workersJWTUtils.createToken(workers);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("token", token);
            return Result.success("登录成功", jsonObject);
        } else {
            return Result.success("登录失败没有此用户");
        }

    }

    /**
     * 维修工人全部订单
     */
    @RequestMapping("billist")
    public Result list(Integer id, Integer pageNum, Integer pageSize) {

        PageInfo<Ordersinfo> ordersinfos = ordersinfoService.findWorkOrderInfoByPage(pageNum, pageSize, id);

        ordersinfos.getList().forEach(
                ordersinfo -> {
                    System.out.println(ordersinfo.getHeatingNumber());
                    ordersinfo.setState(stateService.getById(ordersinfo.getStateId()));
                    ordersinfo.setHeatingNumberObject(heatingNumberService.getById(ordersinfo.getHeatingNumber()));
                    if (ordersinfo.getOrdersPrice() == null) {
                        ordersinfo.setOrdersPrice(0);
                    }
                    System.out.println(ordersinfo.getOrdersPrice());
                }
        );

        return Result.success(ordersinfos);
    }

    /**
     * 维修工人订单详情
     */
    @RequestMapping("detailed")
    public Result infoMation(Integer id) {
        System.out.println(id);
        Ordersinfo ordersinfo = ordersinfoService.findById(id);
        ordersinfo.setState(stateService.getById(ordersinfo.getStateId()));


        return Result.success(ordersinfo);
    }

    @RequestMapping("upd")
    public Result upd(@RequestBody Ordersinfo orderUpd) {
        ordersinfoService.update(orderUpd);
        return Result.success("修改成功");
    }

    @RequestMapping("affirm")
    public Result affirm(Integer id) {
        List<Ordersinfo> ordersinfos = ordersinfoService.findWorkesById(id);
        ordersinfos.forEach(ordersinfo -> {
            System.out.println(ordersinfo.getHeatingNumber());
            ordersinfo.setState(stateService.getById(ordersinfo.getStateId()));
            ordersinfo.setHeatingNumberObject(heatingNumberService.getById(ordersinfo.getHeatingNumber()));
            if (ordersinfo.getOrdersPrice() == null) {
                ordersinfo.setOrdersPrice(0);
            }
            System.out.println(ordersinfo.getOrdersPrice());
        });
        return Result.success(ordersinfos);
    }

    @PostMapping("upload")
    public Result upload(@RequestParam MultipartFile file, Integer id) {
        Ordersinfo ordersinfo = new Ordersinfo();
        ordersinfo.setId(id);
        //将图片保存到本地并获得图片名
        String profile = PictureUtils.picture(file);
        System.out.println(file);
        ordersinfo.setSuccessPicture(profile);
        ordersinfoService.updateById(ordersinfo);
        System.out.println(profile);
        return Result.success(profile);
    }

    @PostMapping("faultType")
    public Result faultType() {
        List<FaultType> faultTypes = faultTypeService.list();
        return Result.success(faultTypes);
    }

    @PostMapping("state")
    public Result state() {
        List<State> states = stateService.list();
        return Result.success(states);
    }

    @PostMapping("materialsType")
    public Result materialsType() {
        List<MaterialsType> materialsTypes = materialsTypeService.list();
        return Result.success(materialsTypes);
    }

    @PostMapping("materialsName")
    public Result materialsName(String materialsTypeName) {
        QueryWrapper<MaterialsType> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MaterialsType::getTitle, materialsTypeName);
        MaterialsType materialsType = materialsTypeService.getOne(queryWrapper);
        QueryWrapper<MaterialsName> queryWrappers = new QueryWrapper<>();
        queryWrappers.lambda().eq(MaterialsName::getMaterialsTypeId, materialsType.getId());
        List<MaterialsName> materialsName = materialsNameService.list(queryWrappers);
        return Result.success(materialsName);
    }

    @PostMapping("save")
    public Result save(String materialsTypeName, String faultTypeName, String materialsName, String stateName, Integer id) {
        System.out.println(materialsTypeName + faultTypeName + materialsName + stateName + id);
        Ordersinfo ordersinfo = new Ordersinfo();
        QueryWrapper<MaterialsType> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MaterialsType::getTitle, materialsTypeName);
        MaterialsType materialsType = materialsTypeService.getOne(queryWrapper);


        QueryWrapper<MaterialsName> queryWrappers = new QueryWrapper<>();
        queryWrappers.lambda().eq(MaterialsName::getTitle, materialsName);
        MaterialsName materialsName1 = materialsNameService.getOne(queryWrappers);

        QueryWrapper<FaultType> faultTypeQueryWrapper = new QueryWrapper<>();
        faultTypeQueryWrapper.lambda().eq(FaultType::getTitle, faultTypeName);
        FaultType faultType = faultTypeService.getOne(faultTypeQueryWrapper);
        System.out.println(faultType.toString());

        QueryWrapper<State> stateQueryWrapper = new QueryWrapper<>();
        stateQueryWrapper.lambda().eq(State::getStateValue, stateName);
        State state = stateService.getOne(stateQueryWrapper);
        ordersinfo.setId(id);
        ordersinfo.setState(state);
        ordersinfo.setFaultType(faultType);
        ordersinfo.setFaultDescription(faultTypeName);

        MaterialsUse materialsUse = new MaterialsUse();
        materialsName1.setMaterialsType(materialsType);
        materialsUse.setMaterialsNameId(materialsName1.getId());
        materialsUse.setOrdersinfoId(ordersinfo.getId());
        materialsUse.setPrice(materialsName1.getPrice());

        materialsUseService.save(materialsUse);

        ordersinfoService.update(ordersinfo);

        return Result.success("成功");
    }

    @RequestMapping("confirm")
    public void confirm(Integer id) {
        Ordersinfo ordersinfo = new Ordersinfo();
        ordersinfo.setId(id);
        ordersinfo.setStateId(3);
        ordersinfoService.updateStateId(ordersinfo);
    }

    @RequestMapping("selectInsert")
    public Result selectInsert(Integer id) {
        return Result.success(materialsUseService.findByOrderId(id));

    }

    @RequestMapping("deletMaterialsUse")
    public Result deletMaterialsUse(Integer id) {
        materialsUseService.removeById(id);
        return Result.success("删除成功");
    }

    @RequestMapping("Completed")
    public Result completed(Integer id){

        return Result.success(ordersinfoService.finndWorksByIdByOrdersinfoId(id,8));
    }
    @RequestMapping("hang")
    public Result hang(Integer id){
        return Result.success(ordersinfoService.hang(id,8));
    }
    @RequestMapping("evaluated")
    public Result evaluated(Integer id){
        return Result.success(ordersinfoService.finndWorksByIdByOrdersinfoId(id,6));
    }
    /**
     * 维修人员抢单功能，为了线程安全添加线程锁
     * 王梓旭 2021-6-22
     * @param workerId 已经登录的维修人员的ID
     * @param orderId  目标订单的ID
     */
    @Synchronized
    @RequestMapping("getTheOrder")
    public Result getTheOrder(Integer workerId,Integer orderId){
        //检查订单是否已经被抢单
        if (false == ordersinfoService.checkOrderHasWorker(orderId)){
            return Result.success("订单已被其他维修人员接单~");
        }
        //向订单中添加维修人员的信息

        return  null;
    }

}
